import {ref, computed, DefineComponent,} from "vue"

export default (initFunc: null | Function = null, resetFunc: null | Function = null, titleend: string = "", emitFunc: Function | null = null) => {
    const showModel = ref(false)    // 弹窗显示控制
    const formValue = ref<{[key:string]:any}>({})       // 表单数据
    const formRef = ref<null|DefineComponent>(null)       // 表单组件
    const editType = ref<"add"|"edit"|"view">("add")        // 编辑、新建、查看
    const result = ref<""|"success"|"failed">("")  // 结果的类型
    const resultText = ref<string | null>(null)    // 交互结果的文字描述
    const loading = ref(false)      // 加载状态
    // 弹窗初始化
    const handleInit = (type: "" | "add" | "edit" | "view", data: any = null) => {          // 初始化
        console.log("handleInit函数触发");
        editType.value = type || "add";
        if (data) {
            formValue.value = data
        }
        initFunc && initFunc(formValue.value);
        showModel.value = true
    }
    // 弹窗关闭
    const handleClose = () => {         // 弹窗关闭
        showModel.value = false
        emitFunc && emitFunc(editType.value)
        handleReset()
    }
    // 弹窗重置
    const handleReset = () => {         // 弹窗重置
        result.value = ""
        resultText.value = ""
        loading.value = false
        editType.value = "add"
        resetFunc && resetFunc()
    }
    // 弹窗标题
    const title = computed(() => {
        switch (editType.value) {
            case "add":
                return "新建" + titleend
            case "edit":
                return "编辑" + titleend
            case "view":
                return "查看" + titleend
            default:
                return "新建" + titleend
        }
    })
    // 交互成功
    const getSuccess = (successText: string) => {
        result.value = "success"
        resultText.value = successText
    }
    // 交互失败
    const getFaild = (error: string) => {
        result.value = "failed"
        resultText.value = error
    }
    // 点击返回
    const handleReturn=()=>{
        result.value = ""
        resultText.value = ""
    }
    return {
        showModel,
        handleInit,
        handleClose,
        handleReset,
        formValue,
        formRef,
        title,
        editType,
        resultText,
        loading,
        getSuccess,
        getFaild,
        handleReturn,
        result,
    }
}
